package com.asia.algorithmcode.dynamicProgram;

/**
 * @DESCRIPTION: 122、买卖股票的最佳时机 2
 * @USER: wanfu
 * @DATE: 2025/6/5 星期四 14:10
 */
public class MaxProfit2 {


    public static void main(String[] args) {
//        int[] arr = {7, 1, 5, 3, 6, 4};
//        int[] arr = {1, 2, 3, 4, 5};
        int[] arr = {5,2,3,2,6,6,2,9,1,0,7,4,5,0};
        System.out.println(new MaxProfit2().maxProfit(arr));
    }


    public int maxProfit(int[] prices) {
        int n = prices.length;
        int minPrice = Integer.MAX_VALUE;
        int income = 0;
        int maxValue = 0;

        for (int i = 0; i < n; i++) {
            if (prices[i] < minPrice) {
                minPrice = prices[i];
            }
            int cur = 0;
            while (i < n && (cur = prices[i] - minPrice) >= maxValue) { // 收益上涨期间
                maxValue = prices[i] - minPrice;
                i++;
            }
            // 收益不在最高点，则卖出
            if (cur < maxValue) {
                income += maxValue;
                if (i < n) {
                    minPrice = prices[i];
                    maxValue = 0;
                }
            } else {
                income += maxValue;
            }
        }
        return income;
    }
}
